package vista;

import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.JPasswordField;
import javax.swing.JButton;
import javax.swing.SwingUtilities;

import modelo.dao.DAO;
import modelo.transfer.Sesion;
import controlador.Controlador;

import java.awt.event.KeyEvent;
import java.awt.event.KeyAdapter;

public class PanelSesion extends JPanel {
	private JTextField textField;
	private JPasswordField passwordField;
	private JPanel actual;
	private DAO dao;
	private Controlador controlador;

	/**
	 * Create the panel.
	 */
	public PanelSesion(DAO d, Controlador c) {
		setBackground(Color.GRAY);
		setSize(1024,768);
		setLayout(null);
		this.actual = this;
		this.dao = d;
		this.controlador = c;
		
		textField = new JTextField();
		textField.setBounds(318, 235, 179, 20);
		add(textField);
		textField.setColumns(10);
		
		passwordField = new JPasswordField();
		passwordField.addKeyListener(new KeyAdapter() {
			@Override
			public void keyPressed(KeyEvent e) {
				int key = e.getKeyCode();
				if (key == KeyEvent.VK_ENTER) {
					((PanelSesion) actual).login(
							textField.getText(),
							passwordField.getPassword()
							);
				}
			}
		});
		passwordField.setBounds(318, 266, 179, 20);
		add(passwordField);
		
		JButton btnLogin = new JButton("Login");
		btnLogin.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				((PanelSesion) actual).login(
						textField.getText(),
						passwordField.getPassword()
						);
			}
		});
		btnLogin.setBounds(365, 309, 89, 23);
		add(btnLogin);
		
		
	}
	
	public void login(String usuario, char[] cs){		
		controlador.getControladorSesion().logIn(usuario, new String(cs));
		Sesion sesion = dao.getDAOSesion().getSesion();
		if (sesion != null){
			// sesion iniciada
			String nombre = sesion.getUsuario().getNombre();
			String password = sesion.getUsuario().getPassword();
			boolean esAdmin = sesion.getUsuario().isAdmin();
			
			if (esAdmin){
				Ventana topFrame = (Ventana) SwingUtilities.getWindowAncestor(actual);
				JPanel next = new PanelUsuarios(dao, controlador);
				topFrame.setContentPane(next);
				
			} else {
				
				Ventana topFrame = (Ventana) SwingUtilities.getWindowAncestor(actual);
				JPanel next = new PanelPrincipal(dao, controlador);
				topFrame.setContentPane(next);
				
			}
			
		} else {
			
			JOptionPane.showConfirmDialog(null, "Usuario no encontrado.", "", JOptionPane.YES_OPTION);
			
		}
	}
}
